import axios from "axios";
import { ElLoading } from "element-plus";
import router from "../router/index";

const service = axios.create({
  baseURL: "https://mall.xiyibaomall.com/xyb/",
  timeout: 50000,
  crossDomain: true,
  withCredentials: true,
});

let loading;
let loadingNum = 0;

//请求加载
function startLoading() {
  if (loadingNum == 0) {
    loading = ElLoading.service({
      lock: true,
      text: "加载中...",
      background: "rgba(255,255,255,0.5)",
    });
  }
  //请求数量加1
  loadingNum++;
}
//请求加载结束
function endLoading() {
  //请求数量减1
  loadingNum--;
  if (loadingNum <= 0) {
    loading.close();
  }
}

service.interceptors.request.use(
  (config) => {
    startLoading();
    if (sessionStorage.getItem("Token")) {
      config.headers["wt"] = sessionStorage.getItem("Token");
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject();
  }
);

service.interceptors.response.use(
  (response) => {
    endLoading();
    if (response.status === 200) {
      if (
        response.data.code == 4000 ||
        response.data.code == 50014 ||
        response.data.code == 50013
      ) {
        // 登录过期，清除token并跳转到登录页
        sessionStorage.removeItem("Token");
        router.replace({
          path: "/login",
          query: { redirect: router.currentRoute.fullPath },
        });
        // 提示用户
        import("element-plus").then(({ ElMessage }) => {
          ElMessage.warning("登录已过期，请重新登录");
        });
      }
      return response.data;
    } else {
      Promise.reject();
    }
  },
  (error) => {
    endLoading();
    if (error.response) {
      switch (error.response.code) {
        case 50014:
        case 4000:
          sessionStorage.removeItem("Token");
          router.replace({
            path: "/login",
          });
          break;
      }
    }
    return Promise.reject(error);
  }
);

export default service;
